<?php

namespace backend\modules\gii\generators\crud;

use Yii;
use yii\gii\CodeFile;

/**
 * Class Generator
 *
 * @package backend\modules\gii\generators\crud
 */
class Generator extends \yii\gii\generators\crud\Generator
{

    public $baseControllerClass = 'common\components\Controller';

    public $formModelClass;

    public $ns;

    public function rules()
    {
        return array_merge(parent::rules(), [
            [['formModelClass'], 'filter', 'filter' => 'trim'],
            [['formModelClass'], 'required'],
            [['formModelClass'], 'compare', 'compareAttribute' => 'searchModelClass', 'operator' => '!==', 'message' => 'Search Model Class must not be equal to Model Class.'],
            [['formModelClass'], 'match', 'pattern' => '/^[\w\\\\]*$/', 'message' => 'Only word characters and backslashes are allowed.'],
        ]);
    }

    /**
     * @inheritdoc
     */
    public function getName()
    {
        return 'Advanced - CRUD Generator';
    }

    /**
     * @inheritdoc
     */
    public function getDescription()
    {
        return 'This generator generates a controller and views that implement CRUD (Create, Read, Update, Delete)
            operations for the specified data model.';
    }

    /**
     * @inheritdoc
     */
    public function generate()
    {
        $controllerFile = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->controllerClass, '\\')) . '.php');

        $files = [
            new CodeFile($controllerFile, $this->render('controller.php')),
        ];

        if (!empty($this->searchModelClass)) {
            $searchModel = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->searchModelClass, '\\') . '.php'));
            $files[] = new CodeFile($searchModel, $this->render('model-search.php'));
        }

        if (!empty($this->formModelClass)) {
            $formModel = Yii::getAlias('@' . str_replace('\\', '/', ltrim($this->formModelClass, '\\') . '.php'));
            $files[] = new CodeFile($formModel, $this->render('model-form.php'));
        }

        return $files;
    }
}
